package com.hbsd.paopaobackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbsd.paopaobackend.common.BaseResponse;
import com.hbsd.paopaobackend.common.ErrorCode;
import com.hbsd.paopaobackend.common.ResultUtils;
import com.hbsd.paopaobackend.exception.BusinessException;
import com.hbsd.paopaobackend.model.domain.User;
import com.hbsd.paopaobackend.model.request.PageInfo;
import com.hbsd.paopaobackend.model.request.User.*;
import com.hbsd.paopaobackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.hbsd.paopaobackend.constant.UserConstant.USER_LOGIN_STATE;
/**
 * 用户接口
 * @author zzh
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
// 配置跨域 allowCredentials: 允许携带cookie
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials = "true")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * RedisTemplate
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @ApiOperation(value = "用户注册", notes = "用户注册接口 register")
    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        if(userRegisterRequest == null) {
            return null;
        }
        // TODO: 注册逻辑
        String userAccount = userRegisterRequest.getUserAccount();
        String getUserPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        // 判断都不能为空
        if(StringUtils.isAllBlank(userAccount, getUserPassword, checkPassword, planetCode)) {
            // 请求参数错误
            // return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            // 抛出异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userAccount, getUserPassword, checkPassword, planetCode);
        if(result == 0) {
            // 注册失败
            return ResultUtils.error(ErrorCode.NULL_ERROR);
        }
        // 返回注册成功的用户id
//        return new BaseResponse<>(0, result, "ok");
        return ResultUtils.success(result);
    }

    @ApiOperation(value = "用户登录", notes = "用户登录接口 userLogin")
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if(userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 校验参数
        if(StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User userResult = userService.userLogin(userAccount, userPassword, request);
        if(userResult == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在");
        }
        return ResultUtils.success(userResult);
    }

    /**
     * 搜索用户数据
     * @param user
     * @return
     */
    @ApiOperation(value = "搜索用户数据", notes = "搜索用户数据接口 searchUsers")
    @PostMapping("/search")
    public BaseResponse<List<User>> searchUsers(@RequestBody User user, HttpServletRequest request) {
        boolean admin = userService.isAdmin(request);
        // 仅管理员可查询
        if (!admin) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.searchUsers(user);
        return ResultUtils.success(users);
    }

    /**
     * 推荐用户数据
     * @param request
     * @return
     */
    @ApiOperation(value = "推荐用户数据", notes = "推荐用户数据接口 recommendUsers")
    @PostMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(@RequestBody PageInfo pageInfo, HttpServletRequest request) {
        Page<User> userPage = userService.recommendUsers(pageInfo, request);
        return ResultUtils.success(userPage);
    }


    /**
     * 删除用户数据
     * @param deleteUserRequest 请求参数
     * @return
     */
    @ApiOperation(value = "删除用户数据", notes = "删除用户数据接口 deleteUser")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteUserRequest deleteUserRequest, HttpServletRequest request) {
        boolean admin = userService.isAdmin(request);
        Long id = deleteUserRequest.getId();
        if(!admin) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限");
        }
        if(id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        // 逻辑删除
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户信息
     * @param request
     * @return 返回用户信息
     */
    @ApiOperation(value = "获取当前用户信息", notes = "获取当前用户信息接口 getCurrentUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Cookie", value = "Cookie", dataType = "string", paramType = "header")}
    )
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
 
        // 强转
        User user  =(User) attribute;
        if(user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        Long id = user.getId();
        // TODO: 校验用户是否合法(比如: 封号)
        User userInfo = userService.getById(id);
        // 返回脱敏后的信息
        User safetyUser = userService.getSafetyUser(userInfo);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @ApiOperation(value = "用户注销(退出登录)", notes = "用户注销接口 logout")
    @PostMapping("/logout")
    public BaseResponse<Integer> logout(HttpServletRequest request) {
        if(request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        int result = userService.userLogout(request);
        return  ResultUtils.success(result);
    }

    /**
     * 更新用户信息
     * @param user
     */
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息接口 userUserListUpdate")
    @PostMapping("/userList/update")
    public BaseResponse<Integer> userUserListUpdate(@RequestBody User user, HttpServletRequest request) {
        // 1、校验参数是否为空
        if(user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 2、更新用户信息
        int result = userService.userListUpdate(user, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新用户信息(欢迎页面)
     * @param userUpdateTagRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息接口(欢迎页面) userUpdateTag")
    @PostMapping("/userList/welcome/updateTag")
    public BaseResponse<Integer> userUserListUpdateTag(@RequestBody UserUpdateTagRequest userUpdateTagRequest, HttpServletRequest request) {
        // 1、校验参数是否为空
        if(userUpdateTagRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 2、更新用户信息
        int result = userService.userUserListUpdateTag(userUpdateTagRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 删除用户信息
     * @param id
     * @return
     */
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息接口 userUserListDelete")
    @PostMapping("/userList/delete/{id}")
    public BaseResponse<Integer> userUserListDelete(@PathVariable Long id) {
        if(id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        return ResultUtils.success(userService.userListDelete(id));
    }


    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @ApiOperation(value = "文件上传", notes = "文件上传接口 uploadFile")
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();

        // 处理文件保存逻辑
        String filePath = userService.saveFile(file, request); // 调用服务方法保存文件
        return ResultUtils.success(filePath);

    }

    /**
     * 根据标签搜索用户
     * @param tagNameList
     * @return
     */
    @ApiOperation(value = "根据标签搜索用户", notes = "根据标签搜索用户接口 searchUsersByTags")
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required  = false) List<String> tagNameList) {
        // 校验参数
        if(CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        List<User> userTags = userService.searchUsersByTagsBySQL(tagNameList);
        return ResultUtils.success(userTags);
    }


    /**
     * 匹配用户
     * @param userMatchRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "匹配用户", notes = "匹配用户接口 matchUsers")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Cookie", value = "Cookie", dataType = "string", paramType = "header")}
    )
    @PostMapping("/match")
    public BaseResponse<List<User>> matchUsers(@RequestBody UserMatchRequest userMatchRequest, HttpServletRequest request) {
        long num = userMatchRequest.getNum();
        if(num <= 0 || num >= 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页数不对");
        }
        User loginUser = userService.getLoginUser(request);
        List<User> userList = userService.matchUsers(num,loginUser);
        return ResultUtils.success(userList);
    }


}

